package Client;

import Shared.ServerInt;
import Shared.User;
import java.awt.Color;
import java.awt.Component;
import java.awt.Image;
import java.rmi.RemoteException;
import java.util.ArrayList;
import static java.util.Collections.list;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.ListCellRenderer;
import javax.swing.ListSelectionModel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import Shared.*;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.util.Enumeration;
import javax.swing.JDialog;
//import sun.misc.PostVMInitHook;

/**
 *
 * @author mosta
 */
public class MainForm extends javax.swing.JFrame {

    /**
     * Creates new form mainForm
     */
    ClientImp client;
    ArrayList<User> fList = new ArrayList<>();
    ArrayList<User> newList = new ArrayList<>();
    ArrayList<String> friendMails = new ArrayList<>();
    DefaultListModel<User> listModel;
    JLabel label = new JLabel();
    User meUser;
    User friendUser;
    public MainForm(ArrayList<User> friendList){
        listModel = new DefaultListModel();
        initComponents();
        try {
            client = new ClientImp();
        } catch (RemoteException ex) {
            System.out.println("System Idle");
            System.exit(0);
        }
        int frameWidth=300;
        int frameHeight=604;
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        this.setBounds((int) screenSize.getWidth() - frameWidth, 0, frameWidth, frameHeight);
        fList = friendList;
        meUser = friendList.get(0);
        setUserStatus(meUser);
        UserName.setText(friendList.get(0).getUserName());
        addFriend();
        try {
            client.checkFriendRequest(meUser.getUserMail());
        } catch (RemoteException ex) {
            Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public MainForm() {
    }
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        OptionPanel = new javax.swing.JPanel();
        status = new javax.swing.JLabel();
        UserName = new javax.swing.JLabel();
        Status = new javax.swing.JComboBox();
        SignOut = new javax.swing.JButton();
        FriendsPanel = new javax.swing.JPanel();
        Friends = new javax.swing.JLabel();
        AddContactPanel = new javax.swing.JPanel();
        Contact = new javax.swing.JButton();
        AreaPanel = new javax.swing.JPanel();
        scrollFriend = new javax.swing.JScrollPane();
        friends = new javax.swing.JList();
        MainMenu = new javax.swing.JMenuBar();
        ChatUp = new javax.swing.JMenu();
        AddContact = new javax.swing.JMenuItem();
        Conversation = new javax.swing.JMenuItem();
        SendMail = new javax.swing.JMenuItem();
        Help = new javax.swing.JMenu();
        About = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setBackground(new java.awt.Color(153, 204, 255));
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });

        OptionPanel.setBackground(new java.awt.Color(153, 0, 76));
        OptionPanel.add(status);

        UserName.setFont(new java.awt.Font("DejaVu Serif Condensed", 1, 14)); // NOI18N
        UserName.setForeground(new java.awt.Color(255, 255, 255));
        UserName.setText("UserName");
        OptionPanel.add(UserName);

        Status.setBackground(new java.awt.Color(255, 255, 255));
        Status.setFont(new java.awt.Font("DejaVu Serif Condensed", 1, 14)); // NOI18N
        Status.setForeground(new java.awt.Color(102, 5, 51));
        Status.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Availabe", "Busy", "Away", "Offline" }));
        Status.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                StatusActionPerformed(evt);
            }
        });
        OptionPanel.add(Status);

        SignOut.setBackground(new java.awt.Color(255, 255, 255));
        SignOut.setFont(new java.awt.Font("DejaVu Serif Condensed", 1, 14)); // NOI18N
        SignOut.setForeground(new java.awt.Color(102, 5, 51));
        SignOut.setText("SignOut");
        SignOut.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                SignOutActionPerformed(evt);
            }
        });
        OptionPanel.add(SignOut);

        FriendsPanel.setBackground(new java.awt.Color(102, 0, 51));

        Friends.setFont(new java.awt.Font("DejaVu Serif Condensed", 1, 18)); // NOI18N
        Friends.setForeground(new java.awt.Color(255, 255, 255));
        Friends.setText("Friends list");
        FriendsPanel.add(Friends);

        AddContactPanel.setLayout(new java.awt.BorderLayout());

        Contact.setBackground(new java.awt.Color(102, 0, 51));
        Contact.setForeground(new java.awt.Color(255, 255, 255));
        Contact.setText("Add Contact");
        Contact.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ContactActionPerformed(evt);
            }
        });
        AddContactPanel.add(Contact, java.awt.BorderLayout.CENTER);

        AreaPanel.setLayout(new java.awt.BorderLayout());

        friends.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        friends.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                friendsMouseClicked(evt);
            }
        });
        friends.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                friendsValueChanged(evt);
            }
        });
        scrollFriend.setViewportView(friends);

        AreaPanel.add(scrollFriend, java.awt.BorderLayout.CENTER);

        MainMenu.setBackground(new java.awt.Color(102, 0, 51));
        MainMenu.setForeground(new java.awt.Color(255, 0, 127));

        ChatUp.setBackground(new java.awt.Color(255, 102, 255));
        ChatUp.setForeground(new java.awt.Color(255, 255, 255));
        ChatUp.setText("ChatUp");

        AddContact.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_A, java.awt.event.InputEvent.ALT_MASK));
        AddContact.setText("Add Contact");
        AddContact.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                AddContactActionPerformed(evt);
            }
        });
        ChatUp.add(AddContact);

        Conversation.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Q, java.awt.event.InputEvent.ALT_MASK));
        Conversation.setText("Conversation");
        Conversation.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ConversationActionPerformed(evt);
            }
        });
        ChatUp.add(Conversation);

        SendMail.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.ALT_MASK));
        SendMail.setText("Send Mail");
        SendMail.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                SendMailActionPerformed(evt);
            }
        });
        ChatUp.add(SendMail);

        MainMenu.add(ChatUp);

        Help.setForeground(new java.awt.Color(255, 255, 255));
        Help.setText("About");

        About.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_A, java.awt.event.InputEvent.ALT_MASK));
        About.setText("About");
        About.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                AboutActionPerformed(evt);
            }
        });
        Help.add(About);

        MainMenu.add(Help);

        setJMenuBar(MainMenu);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(OptionPanel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(FriendsPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(AddContactPanel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(AreaPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(OptionPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(FriendsPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(AreaPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 389, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(AddContactPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void AboutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AboutActionPerformed
        JOptionPane.showMessageDialog(MainForm.this, "<html>Welcome to our Chatting Application <br> Shimaa,Dalia,Belal & Mostafa <br> say Hello :)</html>", "About", JOptionPane.INFORMATION_MESSAGE);
    }//GEN-LAST:event_AboutActionPerformed

    private void AddContactActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AddContactActionPerformed
         AddContact form=new AddContact(meUser, friendMails);
         form.setVisible(true);
    }//GEN-LAST:event_AddContactActionPerformed

    private void ConversationActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ConversationActionPerformed
        // TODO add your handling code here:
        ArrayList<User> onFriend=new ArrayList<>();
        for(int i=0;i<fList.size();i++){
            try {
                if(client.chatFriend(fList.get(i).getUserMail())){
                    onFriend.add(fList.get(i));
                }
            } catch (RemoteException ex) {
                Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        StartConversation con = new StartConversation(onFriend);
        con.setVisible(true);
        con.setDefaultCloseOperation(WIDTH);
    }//GEN-LAST:event_ConversationActionPerformed

    private void SendMailActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SendMailActionPerformed
        // TODO add your handling code here:
        Email e = new Email(meUser.getUserMail());
        e.setVisible(true);
        e.setDefaultCloseOperation(WIDTH);
    }//GEN-LAST:event_SendMailActionPerformed

    private void SignOutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SignOutActionPerformed
        // TODO add your handling code here:
        client.changeStatus(friendMails,meUser.getUserName(),"","Logout",0);
        client.signOut(meUser.getUserMail());
        new SignIn().setVisible(true);
        setVisible(false);
    }//GEN-LAST:event_SignOutActionPerformed

    private void StatusActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_StatusActionPerformed

        String nStatus = null;
        String online = "Images/online.png";
        String offline = "Images/offline.png";
        String busy = "Images/busy.png";
        String away = "Images/away.png";
        if (Status.getSelectedItem().toString().equals("Busy")) {
            nStatus = Status.getSelectedItem().toString();
            Icon icon = new ImageIcon(getClass().getResource(busy));
            status.setIcon(icon);
        } else if (Status.getSelectedItem().toString().equals("Availabe")) {
            nStatus = Status.getSelectedItem().toString();
            Icon icon = new ImageIcon(getClass().getResource(online));
            status.setIcon(icon);
        } else if (Status.getSelectedItem().toString().equals("Away")) {
            nStatus = Status.getSelectedItem().toString();
            Icon icon = new ImageIcon(getClass().getResource(away));
            status.setIcon(icon);
        } else {
            nStatus = Status.getSelectedItem().toString();
            Icon icon = new ImageIcon(getClass().getResource(offline));
            status.setIcon(icon);
        }
        client.changeStatus(friendMails, meUser.getUserMail(),meUser.getUserName(),nStatus, Status.getSelectedIndex()+1);
    }//GEN-LAST:event_StatusActionPerformed

    private void friendsValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_friendsValueChanged

    }//GEN-LAST:event_friendsValueChanged

    private void friendsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_friendsMouseClicked
        if (evt.getClickCount() == 2) {
            int index = friends.locationToIndex(evt.getPoint());
            if (index >= 0) {
                friendUser = listModel.getElementAt(index);
                System.out.println("my:"+friendUser.getUserMail());
                try {
                    if(!(client.chatFriend(friendUser.getUserMail()))){
                        JOptionPane.showMessageDialog(null, "This Person is Offline", "Notification", JOptionPane.INFORMATION_MESSAGE);
                    }else{
                        String ident = meUser.getUserMail() + ":" + friendUser.getUserMail();
                        client.checkIdent(ident, meUser, friendUser);
                    }
                } catch (RemoteException ex) {
                    Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }//GEN-LAST:event_friendsMouseClicked

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed

        //client.signOut(meUser.getUserMail());
        
    }//GEN-LAST:event_formWindowClosed

    private void ContactActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ContactActionPerformed

        AddContact contact = new AddContact(meUser,friendMails);
        contact.setVisible(true);
    }//GEN-LAST:event_ContactActionPerformed
    private void setUserStatus(User user) {
        String online = "Images/online.png";
        String offline = "Images/offline.png";
        String busy = "Images/busy.png";
        String away = "Images/away.png";
        Icon icon1 = new ImageIcon(getClass().getResource(online));
        Icon icon2 = new ImageIcon(getClass().getResource(busy));
        Icon icon3 = new ImageIcon(getClass().getResource(away));
        Icon icon4 = new ImageIcon(getClass().getResource(offline));
        if (user.getStatus() == 1) {
            
            status.setIcon(icon1);
            Status.setSelectedIndex(0);
        } else if (user.getStatus() == 2) {
            
            status.setIcon(icon2);
            Status.setSelectedIndex(1);
        } else if (user.getStatus() == 3) {
           
            status.setIcon(icon3);
            Status.setSelectedIndex(2);
        } else {
           
            status.setIcon(icon4);
            Status.setSelectedIndex(3);
        }
    }
    public void addFriend(){
        try {
         
            String mail =  meUser.getUserMail();
            System.out.println("my mail in addFreind:"+mail);
            fList = client.serverRef.getFriendList(mail);
            //listModel.addElement(meUser);
        } catch (RemoteException ex) {
            Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
        }
        listModel.removeAllElements();
        for (int i = 1; i < fList.size(); i++) {
            listModel.addElement(fList.get(i));
            friendMails.add(fList.get(i).getUserMail());
        }    
        friends.setModel(listModel);
        friends.setCellRenderer(new MyImageList());
        //friends.repaint();
//        friends.revalidate();
        System.out.println("here we gooooo &&&&&");
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem About;
    private javax.swing.JMenuItem AddContact;
    private javax.swing.JPanel AddContactPanel;
    private javax.swing.JPanel AreaPanel;
    private javax.swing.JMenu ChatUp;
    private javax.swing.JButton Contact;
    private javax.swing.JMenuItem Conversation;
    private javax.swing.JLabel Friends;
    private javax.swing.JPanel FriendsPanel;
    private javax.swing.JMenu Help;
    private javax.swing.JMenuBar MainMenu;
    private javax.swing.JPanel OptionPanel;
    private javax.swing.JMenuItem SendMail;
    private javax.swing.JButton SignOut;
    private javax.swing.JComboBox Status;
    private javax.swing.JLabel UserName;
    private javax.swing.JList friends;
    private javax.swing.JScrollPane scrollFriend;
    private javax.swing.JLabel status;
    // End of variables declaration//GEN-END:variables

    public void setStatusForFriend(String mail,String status){
        
        for(int i=0;i<fList.size();i++){
            System.out.println("hi belal change status");
            if(fList.get(i).getUserMail().equals(mail)){
                if(status.equals("Availabe")){
                    fList.get(i).setStatus(1);
                }else if(status.equals("Busy")){
                    fList.get(i).setStatus(2);
                }else if(status.equals("Away")){
                    fList.get(i).setStatus(3);
                }else{
                     fList.get(i).setStatus(3);
                }
            }
        }
        
       //friends.repaint();
    }
    class MyImageList implements ListCellRenderer<User> {

        @Override
        public Component getListCellRendererComponent(JList JList, User e, int i, boolean bln, boolean bln1) {
            Color background = null;
            Color foreground = null;
            String signin = "Images/signin.jpeg";
            String online = "Images/online.png";
            String offline = "Images/offline.png";
            String busy = "Images/busy.png";
            String away = "Images/away.png";
            Icon icon1 = new ImageIcon(getClass().getResource(online));
            Icon icon2 = new ImageIcon(getClass().getResource(busy));
            Icon icon3 = new ImageIcon(getClass().getResource(away));
            Icon icon4 = new ImageIcon(getClass().getResource(offline));

            label.setText(e.toString());
            switch (e.getStatus()) {
                case 1:
                    label.setIcon(icon1);
                    break;
                case 2:
                    label.setIcon(icon2);
                    break;
                case 3:
                    label.setIcon(icon3);
                    break;
                default:
                    label.setIcon(icon4);
                    break;
            }

            if (bln) {
                background = Color.BLACK;
                foreground = Color.RED;
            } else {
                background = Color.WHITE;
                foreground = Color.BLACK;
            }
            label.setBackground(background);
            label.setForeground(foreground);
            return label;
        }
    }
}
